<template>
  <div class="container">
    <div class="container-1200">
      <div class="title mg-B20">编辑企业资料</div>
      <div>
        <div style="color: red; margin-left: 20px;">审核状态：{{companyStatusFormate(companyInfoForm.status)}}</div>
        <div style="color: red; margin-left: 20px;" v-if="companyInfoForm.memo">驳回说明：{{companyInfoForm.memo}}</div>
      </div>
      <el-form
        :model="companyInfoForm"
        :rules="companyInfoRules"
        ref="companyInfoForm"
      >
        <div>
          <el-row class="rowBorder rowTopBorder">
            <el-col :span="4" class="col-flex request bg-ccc">企业名称</el-col>
            <el-col :span="8" class="col-flex colLeftBorder colRightBorder">
              <el-form-item prop="name" class="vali">
                <el-input v-model="companyInfoForm.name"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="col-flex request bg-ccc">统一社会信用代码</el-col>
            <el-col :span="8" class="col-flex colLeftBorder">
              <el-form-item prop="code" class="vali">
                <el-input v-model="companyInfoForm.code"> </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="rowBorder">
            <el-col :span="4" class="col-flex request bg-ccc">法定代表人</el-col>
            <el-col :span="8" class="col-flex colLeftBorder colRightBorder">
              <el-form-item prop="legalPerson" class="vali">
                <el-input v-model="companyInfoForm.legalPerson"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="col-flex request bg-ccc">注册资本(万元)</el-col>
            <el-col :span="8" class="col-flex colLeftBorder">
              <el-form-item prop="capital" class="vali">
                <el-input v-model="companyInfoForm.capital" type="number">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="rowBorder">
            <el-col :span="4" class="col-flex request bg-ccc">负责人</el-col>
            <el-col :span="8" class="col-flex colLeftBorder colRightBorder">
              <el-form-item prop="linkman" class="vali">
                <el-input v-model="companyInfoForm.linkman"> </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="col-flex request bg-ccc">负责人联系方式</el-col>
            <el-col :span="8" class="col-flex colLeftBorder">
              <el-form-item prop="phone" class="vali">
                <el-input v-model="companyInfoForm.phone"> </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="rowBorder">
            <el-col :span="4" class="col-flex request bg-ccc">注册地址</el-col>
            <el-col :span="20" class="col-flex colLeftBorder">
              <el-form-item prop="registerAddress" class="vali">
                <el-input v-model="companyInfoForm.registerAddress"> </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="rowBorder">
            <el-col :span="4" class="col-flex request bg-ccc">办公地址</el-col>
            <el-col :span="20" class="col-flex colLeftBorder">
              <el-form-item prop="officeAddress" class="vali">
                <el-input v-model="companyInfoForm.officeAddress"> </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="rowBorder">
            <el-col :span="4" class="col-flex bg-ccc">行业类别</el-col>
            <el-col :span="8" class="col-flex colLeftBorder colRightBorder">
              <el-form-item prop="industry" class="vali">
                <el-select
                  v-model="companyInfoForm.industry"
                  placeholder="点击选择行业类别"
                >
                  <el-option
                    v-for="item in industryDict"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="col-flex request bg-ccc">注册类型</el-col>
            <el-col :span="8" class="col-flex colLeftBorder">
              <el-form-item prop="registration" class="vali">
                <el-select
                  v-model="companyInfoForm.registration"
                  placeholder="点击选择企业等级注册类型"
                >
                  <el-option
                    v-for="item in registrationDict"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="rowBorder">
            <el-col :span="4" class="col-flex request bg-ccc">纳税类型</el-col>
            <el-col :span="8" class="col-flex colLeftBorder colRightBorder">
              <el-form-item prop="taxType" class="vali">
                <el-select
                  v-model="companyInfoForm.taxType"
                  placeholder="点击选择企业等级注册类型"
                >
                  <el-option
                    v-for="item in taxTypeDict"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="col-flex request bg-ccc">所属部门</el-col>
            <el-col :span="8" class="col-flex colLeftBorder">
              <el-form-item prop="officeId" class="vali">
                <el-select
                  v-model="companyInfoForm.officeId"
                  placeholder="点击选择所属部门"
                >
                  <el-option
                    v-for="item in offices"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
          </el-row>
          <!-- <el-row class="rowBorder">
            <el-col :span="4" class="col-flex">企业状态</el-col>
            <el-col
              :span="8"
              class="col-flex colLeftBorder colRightBorder leftAlign-pd15"
            >
              {{ companyStatusFormate(companyInfoForm.status) }}
            </el-col>
            <el-col :span="4" class="col-flex">驳回说明</el-col>
            <el-col :span="8" class="col-flex colLeftBorder leftAlign-pd15">
              {{ companyInfoForm.memo }}
            </el-col>
          </el-row> -->
          <el-row class="rowBorder bg-ccc">
            <el-col :span="4" class="">
              <div>
                <div class="textCenter request">营业执照</div>
                <!-- <div class="textCenter">
              (点击下载)
            </div> -->
              </div></el-col
            >
            <el-col
              :span="20"
              class="col-flex leftAlign-pd30 colLeftBorder bg-fff"
            >
              <div style="margin:10px">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="meta"
                  placeholder="请上传营业执照"
                  error="请上传营业执照"
                  fit="contain"
                >
                </el-image>
                <div class="flexWithJusCenter">
                   <el-link :href="meta" target="_blank" type="primary" class="link">营业执照</el-link> 
                </div>
              </div>
              <div class="mg-L20">
              <el-form-item prop="meta">
                <singleFileUpload @returnUrl="returnUrl"
              ></singleFileUpload>
              </el-form-item>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="mg-T20">
          <el-form-item class="mg-T20">
            <el-button type="primary" @click="onSave('companyInfoForm')"
              >保存为草稿</el-button
            >
            <el-button
              type="primary"
              @click="onSaveAndSubmit('companyInfoForm')"
              >保存并提交</el-button
            >
            <el-button @click="back">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { update as companyUpdate, find as companyFind } from "@/api/company";
import { submit as submitCompany } from "@/api/adminCompany";
import { list as dictList } from "@/api/dict";
import fileUpload from "@/components/Upload/fileUpload";
import singleFileUpload from "@/components/Upload/singleFileUpload";
import utils from "@/utils/utils.js";
import { validPhone, validPositiveInt } from "@/utils/validate.js";
import { list as officeList } from "@/api/sysOffice";
import { save as companySave } from "@/api/company";

export default {
  components: { fileUpload,singleFileUpload },
  name: "companyEdit",
  data() {
    const validatePhone = (rule, value, callback) => {
      if (utils.isNull(value)) {
        callback(new Error("请输入负责人号码"));
      } else if (!validPhone(value)) {
        callback(new Error("负责人手机号码不正确"));
      } else {
        callback();
      }
    };

    const validateCapital = (rule, value, callback) => {
      if (utils.isNull(value)) {
        callback(new Error("请输入注册资本"));
      } else if (!validPositiveInt(value)) {
        callback(new Error("注册资本必须为大于0的数值"));
      } else {
        callback();
      }
    };

    return {
      meta: "",
      companyId: "",
      companyInfoForm: {
        code: "",
        name: "",
        legalPerson: "",
        capital: "",
        linkman: "",
        phone: "",
        registerAddress: "",
        officeAddress: "",
        industry: "",
        registration: "",
        taxType: "",
        status: "",
        memo: "",
        deleted: "",
        officeId: "",
        userId: "",
        meta: "",
        createBy: "",
        modifyBy: "",
      },
      companyInfoRules: {
        name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
        code: [
          { required: true, message: "请输入营业执照编码", trigger: "blur" },
        ],
        legalPerson: [
          { required: true, message: "请输入法定代表人", trigger: "blur" },
        ],
        capital: [
          { required: true, validator: validateCapital, trigger: "blur" },
        ],
        linkman: [{ required: true, message: "请输入负责人", trigger: "blur" }],
        phone: [
          { required: true, validator: validatePhone, trigger: "blur" },
          // { required: true, message: "请输入负责人号码", trigger: "blur" },
        ],
        registration: [
          { required: true, message: "请选择注册类型", trigger: "blur" },
        ],
        taxType: [
          { required: true, message: "请选择纳税类型", trigger: "blur" },
        ],
        registerAddress: [
          { required: true, message: "请输入注册地址", trigger: "blur" },
        ],
        officeAddress: [
          { required: true, message: "请输入办公地址", trigger: "blur" },
        ],
        officeId: [
          { required: true, message: "请输入所属部门", trigger: "blur" },
        ],
      },

      //部门列表
      offices: [],

      //字典数据
      taxTypeDict: [],
      registrationDict: [],
      companyStatusDict: [],
      industryDict: [],

      //获取字典的promise
      taxTypeDictPromise: "",
      registrationDictPromise: "",
      companyStatusDictPromise: "",
      officeListPromise: "",

      path: "",
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.path = route.path
      },
      immediate: true,
    },
  },

  activated(){
    console.log('activated执行了--',);
    if(this.$store.getters.closeAliveName == "companyEdit"){
      console.log('activated执行了--',this.$store.getters);
      this.companyId = this.$route.query.companyId
      this.companyFind(this.companyId);
      this.$store.dispatch("user/cleanCloseAliveName")
    }
  },

  created() {
    console.log('created执行了--',);
    if (this.$route.query) {
      this.companyId = this.$route.query.companyId;
    }
    this.taxTypeDictPromise = utils.getDictList("tax_type", (res) => {
      this.taxTypeDict = res.data;
    });
    this.registrationDictPromise = utils.getDictList("registration", (res) => {
      this.registrationDict = res.data;
    });
    this.companyStatusDictPromise = utils.getDictList(
      "company_status",
      (res) => {
        this.companyStatusDict = res.data;
      }
    );
    this.industryDictPromise = utils.getDictList("industry", (res) => {
      this.industryDict = res.data;
    });
    this.officeListPromise = this.officeList();
  },

  mounted() {
    console.log('mounted执行了--',);
    Promise.all([
      this.taxTypeDictPromise,
      this.registrationDictPromise,
      this.companyStatusDictPromise,
      this.officeListPromise,
      this.industryDictPromise,
    ]).then((res) => {
      //console.log("字典已经全部加载完成--");
      if (this.$route.query) {
        this.companyId = this.$route.query.companyId;
        this.companyFind(this.companyId);
      }
    });
  },

  destroyed() {},

  methods: {
    removeItem(index) {
      this.meta.splice(index, 1);
    },

    returnUrl(data) {
      console.log("data--", data);
      this.meta = data.url;
    },
    //获取公司信息
    companyFind(id) {
      companyFind(id).then((res) => {
        console.log("获取公司信息res--", res);
        if (res.type == "success") {
          if (!utils.isNull(res.data.company.meta)) {
            this.meta = res.data.company.meta;
          }else{
            this.meta = ""
          }
          this.companyInfoForm = res.data.company;
        }
      });
    },

    //保存并提交
    onSaveAndSubmit(formName) {
      this.companyInfoForm.status = 1;
      this.onSubmit(formName, () => {
        this.$message.success("企业资料提交成功");
      });
    },

    onSave(formName) {
      this.companyInfoForm.status = 0;
      this.onSubmit(formName, () => {
        this.$message.success("企业资料保存成功");
      });
    },

    //表单提交事件
    onSubmit(formName, callback) {
      let _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!utils.isNull(_this.meta)) {
            _this.companyInfoForm.meta = _this.meta;
            companyUpdate(this.companyInfoForm)
            .then((res) => {
              console.log("companySave成功获取数据--", res);
              this.$store.dispatch("user/setCloseView", this.path)
              if (res.type == "success") {
                this.$router.push({ path: "/company/list" });
                if (callback) {
                  callback(res);
                }
              }
            })
            .catch((err) => {
              this.$message.error(err.msg);
            });
          }else{
            this.$notify.error({
              title: '提示',
              message: '请上传营业执照',
            });
          }
          
        }
      });
    },

    back() {
      this.$router.go(-1);
    },

    officeList() {
      let _this = this;
      let params = new URLSearchParams();
      params.append("menuType", 0);
      return officeList(params)
        .then((response) => {
          console.log(response);
          _this.offices = response.data;
        })
        .catch((error) => {
          console.log("error!!");
        });
    },

    //字典数据格式化
    taxTypeFormate(data) {
      return utils.selectDictLabel(this.taxTypeDict, data);
    },

    registrationFormate(data) {
      return utils.selectDictLabel(this.registrationDict, data);
    },

    companyStatusFormate(data) {
      return utils.selectDictLabel(
        this.companyStatusDict,
        "company_status-" + data
      );
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .vali .el-form-item__content .el-form-item__error {
  top: 5px !important;
  right: 30px !important;
  left: unset !important;
  // left: 80% !important;
}

/deep/ .el-date-editor {
  width: 100%;
}

/deep/ .el-date-editor .el-input__inner {
  padding-right: 0px !important;
}

/deep/ .el-input__inner {
  border: 1px solid #fff !important;
}

.el-select {
  width: 100%;
}
.el-form-item {
  margin: 0;
  width: 100%;
}
</style>
